#ifndef __M_CONNECTION_H__
#define __M_CONNECTION_H__


#include "muduo/proto/dispatcher.h"
#include "muduo/proto/codec.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include"muduo/net/EventLoopThread.h"
#include"muduo/base/CountDownLatch.h"
#include<iostream>

#include"mq_channel.hpp"
#include"mq_worker.hpp"

namespace xiang11mq
{
class Client
{
public:
    using ptr = std::shared_ptr<Client>;
    using ProtobufCodecPtr = std::shared_ptr<ProtobufCodec>;

    Client(const std::string& sip, int port, const AsyncWorker::ptr &worker)
        :_latch(1)
        ,_client(worker->loopthread.startLoop(), muduo::net::InetAddress(sip, port), "Client")
        ,_dispatcher(std::bind(&Client::onUnknownMessage,
         this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
        ,_codec(std::make_shared<ProtobufCodec>(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, 
         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)))
        ,_worker(worker)
        ,_channel_manager(std::make_shared<ChannelManager>())
    {
        //注册业务请求处理函数 
        _dispatcher.registerMessageCallback<xiang11mq::basicConsumerResponse>(std::bind(&Client::basicConsumerResponse, this,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _dispatcher.registerMessageCallback<xiang11mq::basicCommonResponse>(std::bind(&Client::basicCommonResponse, this,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, _codec.get(),
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.setConnectionCallback(std::bind(&Client::onConnection, this,
        std::placeholders::_1));

        //需要等待链接成功后再返回 阻塞等待用latch
        _client.connect();  //会直接返回
        _latch.wait();      //阻塞等待 直到链接成功
    }



    Channel::ptr openChannel()
    {
        if(_conn.get() == nullptr)
        {
            DLOG("_conn服务端连接实例化对象为空");
            return Channel::ptr();
        }
        Channel::ptr channel = _channel_manager->create(_conn, _codec);
        bool ret = channel->openChannel();
        if(ret == false)
        {
            DLOG("客户端希望服务端打开信道失败");
            return Channel::ptr();
        }
        return channel;
    }
    void closeChannel(const Channel::ptr &channel)
    {
        std::string cid = channel->cid();
        channel->closeChannel();
        _channel_manager->remove(cid);
    }
private:
    bool send(const google::protobuf::Message *message)
    {
        if (_conn->connected())
        { // 连接状态正常，再发送，否则就返回false
            _codec->send(_conn, *message);
            return true;
        }
        return false;
    }
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            _conn = conn;
            DLOG("_conn = conn 步骤成功");
            _latch.countDown(); //唤醒主线程阻塞
            if (conn.get() == nullptr)
            {
                DLOG("服务端传来连接对象为空");
                return;
            }

            if (_conn.get() == nullptr)
            {
                DLOG("服务端连接实例化对象为空");
                return;
            }
        }
        else
        {
            //链接关闭时的操作
            DLOG("链接关闭, _conn.reset()")
            _conn.reset();
        }
    }
    //基础响应
    void basicCommonResponse(const muduo::net::TcpConnectionPtr &conn, const basicCommonResponsePtr &message, muduo::Timestamp)
    {
        //1.找到信道
        Channel::ptr channel = _channel_manager->get(message->cid());
        if(channel.get() == nullptr)
        {
            DLOG("未找到信道信息: %s", message->cid().c_str());
            return;
        }
        //2.将得到的响应对象 添加到信道基础响应的hash_map中
        channel->putBasicResponse(message);
    }
    //消费响应
    void basicConsumerResponse(const muduo::net::TcpConnectionPtr &conn, const basicConsumerResponsePtr &message, muduo::Timestamp)
    {
        //1.找到信道
        Channel::ptr channel = _channel_manager->get(message->cid());
        if(channel.get() == nullptr)
        {
            DLOG("未找到信道信息");
            return;
        }
        //2.封装异步任务 抛入线程池
        _worker->pool.push([channel, message](){
            channel->consume(message);
        });
    }
        //收到消息时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        std::cout << "翻译结果：" << buf->retrieveAllAsString() << std::endl;
    }
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }
private:
    muduo::CountDownLatch _latch;                   //实现同步
    muduo::net::TcpClient _client;                  //客户端
    muduo::net::TcpConnectionPtr _conn;             //客户对应链接
    ProtobufDispatcher _dispatcher;                 //分发器
    ProtobufCodecPtr _codec;                           //协议处理器
    AsyncWorker::ptr _worker;                       //异步工作线程
    ChannelManager::ptr _channel_manager;

};

}

#endif